# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  # Pick a unique cookie name to distinguish our session data from others'
  session :session_key => '_bill_tracker_session_id'

  def redirect_home
    if current_user
      redirect_to :controller => 'user', :action => 'home'
    else
      redirect_to :controller => 'user', :action => 'login'
    end
  end
  
  def require_user
    unless current_user
      flash[:error] = 'You must be logged in to access this area.' unless params[:controller] == 'user' && params[:action] == 'home'
      redirect_to :controller => 'user', :action => 'login'
    end
  end
  
  def require_admin
    if current_user && current_user.is_admin?
      true
    else
      flash[:error] = 'You must be an admin.'
      redirect_home
    end
  end

protected
  def current_user
    @current_user ||= User.find(session[:current_user]) if session[:current_user]
  rescue
    session[:current_user] = nil
    redirect_to :controller => 'user', :action => 'login'
  end
  helper_method :current_user
end
